package zww.study.basic;

public class StringBuilderStudy {
    /*StringBuilder类*/
    public static void main(String[] args) {
        /*
         * StringBuilder是一個可变的字符串类；
         * 可以看作一个容器;
         * StringBuilder的创建的对象的内容是可变的
         * String的内容是不可变的
         * */
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:" + sb);
        System.out.println("sb.length():" + sb.length());

        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());

        // 成员方法：StringBuilder.append() 追加数据
        //         StringBuilder.reverse() 返回相反的字符序列
        //链式编程
        sb.append("hello").append("world").append("java").append(100);
        System.out.println("sb:" + sb); //public StringBuilder reverse()：返回相反的字符序列 sb.reverse();
        System.out.println("sb:" + sb);

        /*
         *  StringBuilder 和 String 相互转换
         * */
        StringBuilder sb1 = new StringBuilder();
        sb1.append("hello");
        String s2 = sb1.toString();
        // StringBuilder 通过成员方法toString()返回string
        String s3 = "hello";
        StringBuilder sb3 = new StringBuilder(s3);
        // Sting传入StringBuilder的构造方法实现Strig转换为StringBuilder
        int[] arr = {1, 2, 3};
        String sarr = arrayTostring(arr);
        System.out.println(sarr);

    }

/*
* 数组转字符串,返回特定形式的字符串拼接
* */
    public static String arrayTostring(int[] arr) {
        StringBuilder sbarr = new StringBuilder();
        sbarr.append("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                sbarr.append(arr[i]);
            } else {
                sbarr.append(arr[i]).append(",");
            }
        }
        sbarr.append("]");
        String s = sbarr.toString();
        return s;
    }

}
